import React, { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import cn from "classnames";
import { observer } from "mobx-react-lite";
import cls from "./CommonModal.module.scss";
import { scroll } from "./scroll";

export interface CommonModalPropsI {
  isOpen: boolean;
  close: () => void;
  onClose?: () => void;
  children?: React.ReactNode;
  rootChildren?: React.ReactNode;
  rootClass?: string;
  containerClass?: string;
  backdropClass?: string;
}

const root = document.querySelector("#modal-root") as Element;

export const CommonModal: React.FC<CommonModalPropsI> = observer(
  ({
    isOpen,
    onClose,
    close,
    children,
    rootClass,
    containerClass,
    backdropClass,
    rootChildren,
  }) => {
    const [waitAnimation, setWaitAnimation] = useState<boolean>(isOpen);

    useEffect(() => {
      let timer = 0;

      if (!isOpen) {
        timer = window.setTimeout(() => {
          setWaitAnimation(false);
        }, 300);
      } else {
        timer = window.setTimeout(() => {
          setWaitAnimation(true);
        }, 0);
      }

      return () => {
        clearTimeout(timer);
      };
    }, [isOpen]);

    useEffect(() => {
      if (isOpen) {
        scroll.disable();
      } else {
        scroll.enable();
      }

      return () => {
        scroll.enable();
      };
    }, [isOpen]);

    const handleClose = () => {
      if (onClose) {
        onClose();
      }

      close();
    };

    return isOpen || waitAnimation
      ? createPortal(
          <section
            className={cn(cls.root, rootClass)}
            data-open={isOpen ? waitAnimation : isOpen}
          >
            <button
              className={cn(cls.backdrop, backdropClass)}
              type="button"
              onClick={handleClose}
            />
            <div className={cn(cls.container, containerClass)}>{children}</div>
            {rootChildren}
          </section>,
          root
        )
      : null;
  }
);

CommonModal.displayName = "CommonModal";
CommonModal.defaultProps = {
  children: "",
  rootClass: "",
  containerClass: "",
};
